$(function () {
    //浏览器调试
    let JIM = new JMessage();
    let markId = getUrlString('markid');
    let username;
    // let username = 'djuser_161360';
    let password;
    let appkey,random_str,signature,timestamp;


    //添加
    $("#addFriend").click(function () {
        $('.addAlert').fadeIn();
    });

    $('.addAlert .shade').click(function () {
        $('.addAlert').fadeOut();
    });

    //获取appid
    function getAppid() {
        layLoading();
        getData('post','/niu/apiv3/member_jmauth.php',{'markid':markId},function (data) {
            console.log(data);
            username = data.imid;
            password = data.impw;
            appkey = data.appkey;
            random_str = data.random_str;
            signature = data.signature;
            timestamp = data.timestamp;
            //调用初始化
            init();
        })
    }
    getAppid();

    //初始化
    function init() {
        JIM.init({
            "appkey" : appkey,
            "random_str" : random_str,
            "signature" : signature,
            "timestamp" : timestamp,
            "flag" : 0
        }).onSuccess(function(data) {
            console.log(data);
            login(username,password);
            //断线监听
            JIM.onDisconnect(function(){
                window.location.reload()
                // laymsg('您已断线，请重新登录')
            });
            //data.code 返回码
            //data.message 描述
        }).onFail(function(data) {
            codeError(data.code)
            // laymsg(data.message);

        });
    }

    //登录
    function login(username,password) {

        JIM.login({
            'username' : username,
            'password': password
        }).onSuccess(function(data) {
            console.log(data);
            getConversation();
            JIM.onMsgReceive(function(data) {
                data = JSON.stringify(data);
                console.log('1msg_receive:' + data);

            });

            //消息已读数变更事件实时监听
            JIM.onMsgReceiptChange(function(data) {
                console.log(data);
                // data.type
                // data.gid
                // data.appkey
                // data.username
                // data.receipt_msgs[].msg_id
                // data.receipt_msgs[].unread_count
            });


            JIM.onEventNotification(function(data) {
                // console.log('event_receive: ' + JSON.stringify(data));
            });

            JIM.onSyncConversation(function(data) { //离线消息同步监听
                // console.log( data);
            });

            JIM.onUserInfUpdate(function(data) {
                console.log('onUserInfUpdate : ' + JSON.stringify(data));
            });

            JIM.onSyncEvent(function(data) {
                console.log('onSyncEvent : ' + JSON.stringify(data));
            });

            JIM.onMsgReceiptChange(function(data){
                console.log('onMsgReceiptChange : ' + JSON.stringify(data));

            });

            JIM.onSyncMsgReceipt(function(data){
                console.log('onSyncMsgReceipt : ' + JSON.stringify(data));

            });

            JIM.onMutiUnreadMsgUpdate(function(data){
                console.log('onConversationUpdate : ' + JSON.stringify(data));

            });

            JIM.onTransMsgRec(function(data){
                console.log('onTransMsgRec : ' + JSON.stringify(data));
            });

            JIM.onRoomMsg (function(data){
                console.log('onRoomMsg  : ' + JSON.stringify(data));
            });





        }).onFail(function(data) {
            codeError(data.code)
        }).onTimeout(function(data) {
            console.log('timeout:' + JSON.stringify(data));
        });
    }


    //获取会话列表
    function getConversation() {
        JIM.getConversation().onSuccess(function(data) {
            layer.closeAll('loading');
            console.log(data);
            var append = '';
            $(data.conversations).each(function (index) {
                if (this.type === 4){
                    append += '<li>' +
                        '                <div class="left">' +
                        '                    <img src="../../res/img/messages/headPic.png" alt="">' +
                        '                </div>' +
                        '                <div class="right">' +
                        '                    <p class="username">' +
                        '                   <span>'+this.name+'</span>' +
                        '                        <span class="time">'+getTsFormatDate(this.mtime)+'</span>' +
                        '                    </p>' +
                        '                    <p class="userContent">' ;
                    // '                        <span class="messageContent">带着与家人没什么区别的猫精灵帕克当随带着与家人没什么区别的猫精灵帕克当随…</span>' +
                    if(this.unread_msg_count !== 0){
                        append += '                        <span class="number">'+this.unread_msg_count+'</span>';
                    }
                    append += '                    </p>' +
                        '                </div>' +
                        '            </li>';
                } else if(this.type === 3){
                    append += '<li>' +
                        '       <input class="name" type="hidden" value="'+this.name+'">'+
                        '                <div class="left">' +
                        '                    <img src="../../res/img/eggTV/1.png" alt="">' +
                        '                </div>' +
                        '                <div class="right">' +
                        '                    <p class="username">' +
                        '                        <span>'+this.nickName+'</span>' +
                        '                        <span class="time">'+getTsFormatDate(this.mtime)+'</span>' +
                        '                    </p>' +
                        '                    <p class="userContent">' ;
                    // '                        <span class="messageContent">带着与家人没什么区别的猫精灵帕克当随带着与家人没什么区别的猫精灵帕克当随…</span>' +
                    if(this.unread_msg_count !== 0){
                        append += '                        <span class="number">'+this.unread_msg_count+'</span>';
                    }
                    append += '                    </p>' +
                        '                </div>' +
                        '            </li>';
                    getResource(this.avatar).then(function(successData) {
                        $("#conversationList li").eq(index).find('.left').find('img').attr('src',successData);
                    });
                }
            });
            $('#conversationList').append(append);
            $('#conversationList li').click(function () {
                let toUserName = $(this).find('.name').val();
                window.location.href = 'dancool://web=https://api.odancool.com/weixinapp/view/messages/sessionList.html?tousername='+toUserName+'&username='+username
            });
        }).onFail(function(data) {
            codeError(data.code)
        });
    }

    //获取用户的个人信息
    function getSelfInfo(username,isMe) {
        JIM.getUserInfo({
            'username' : username
        }).onSuccess(function(data) {
            console.log(data);
                getResource(data.user_info.avatar).then(function(successData) {

                })
        }).onFail(function(data) {
            codeError(data.code)
            console.log(data);
        });

    }

    //获取图片资源
    function getResource (media_id) {
        return new Promise(function(success,fail) {
            JIM.getResource({
                'media_id' : media_id,
            }).onSuccess(function(data) {
                // console.log(data);
                success(data.url)
                //data.code 返回码
                //data.message 描述
                //data.url 资源临时访问路径，具体超时时间expire time会包含在url中
            }).onFail(function(data) {
                codeError(data.code)
                //data.code 返回码
                //data.message 描述
            });
        });
    }
});